package com.wwwarehouse.contract.contract;

import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.custom_widget.ClearEditText;
import com.wwwarehouse.common.custom_widget.textinput.TextInputLayout;
import com.wwwarehouse.common.tools.rsa.StringUtils;
import com.wwwarehouse.contract.bean.PayMentItemBean;
import com.wwwarehouse.contract.core.ContractConstant;
import com.wwwarehouse.contract.customview.AutoClickButton;
import com.wwwarehouse.contract.event.PayItemEvent;
import com.wwwarehouse.contract.event.RefreshPublishGoodsEvent;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import contract.wwwarehouse.com.contract.R;
import de.greenrobot.event.EventBus;

import static com.tencent.smtt.sdk.TbsReaderView.TAG;

/**
 * Description:
 * Copyright  : Copyright (c) 2017
 * Author     : yfwang
 * Date       : 2017/10/19 10:12
 */
public class PayItemMessageFragment extends TheParentFragment implements View.OnClickListener {
    private RelativeLayout mRelPlaceOrder;
    private TextView mPlace;
    private ImageView mCheckBox;
    private ClearEditText mAlipay;
    private ClearEditText mWechatPay;
    private ClearEditText mBankName;
    private ClearEditText mBankWhere;
    private ClearEditText mBankNumber;
    private AutoClickButton mConfirm;

    private PayMentItemBean.DataBean bean;
    private TextInputLayout mAlipayLayout;
    private TextInputLayout mWechatLayout;
    private TextInputLayout mBankNameLayout;
    private TextInputLayout mBankLayout;
    private TextInputLayout mBankNumLayout;
	private String specialSym = "^[a-zA-Z0-9\\u4E00-\\u9FA5]+$"; //特殊符号

    private boolean isAliPaly = true;
    private boolean isWechatPay = true;
    private boolean isBankName = true;
    private boolean isBankWhere = true;
    private boolean isBankNum = true;
    private String mPbUkid;
    private boolean isOneInput; //至少有一个填了
	private String mContractUkid;


	private List<TextView> texts = new ArrayList<>();

    @Override
    protected int getContentId() {
        return R.layout.fragment_pay_item_msg;
    }

    @Override
    public void setTitle() {
        if (peekFragment() instanceof PayItemMessageFragment) {
            mActivity.setTitle("设置支付项");
        }
    }

    @Override
    protected void init(View view) {
        mAlipay = (ClearEditText) view.findViewById(R.id.alipay);
        mWechatPay = (ClearEditText) view.findViewById(R.id.wechat_pay);
        mBankName = (ClearEditText) view.findViewById(R.id.bank_name);
        mBankWhere = (ClearEditText) view.findViewById(R.id.bank);
        mBankNumber = (ClearEditText) view.findViewById(R.id.bank_number);
        mRelPlaceOrder = (RelativeLayout) view.findViewById(R.id.rel_place_order);
        mAlipayLayout = (TextInputLayout) view.findViewById(R.id.alipay_layout);
        mCheckBox = (ImageView) view.findViewById(R.id.iv_checkbox);
        mPlace = (TextView) view.findViewById(R.id.tv_place);
        mConfirm = (AutoClickButton) view.findViewById(R.id.confirm_btn);
        mConfirm.setOnClickListener(this);
        mWechatLayout = (TextInputLayout) view.findViewById(R.id.wechat_layout);
        mBankNameLayout = (TextInputLayout) view.findViewById(R.id.bank_name_layout);
        mBankLayout = (TextInputLayout) view.findViewById(R.id.bank_layout);
        mBankNumLayout = (TextInputLayout) view.findViewById(R.id.bank_num_layout);
        texts.add(mBankName);
        texts.add(mBankWhere);
        texts.add(mBankNumber);
        if (getArguments() != null && getArguments().getSerializable(ContractConstant.KEY_BUNDLE_PAYMENTS) != null) {
            bean = (PayMentItemBean.DataBean) getArguments().getSerializable(ContractConstant.KEY_BUNDLE_PAYMENTS);
            if (bean != null) {
//                支付宝账号
                if (StringUtils.isNoneNullString(bean.getAccountAlipay())) {
                    mAlipay.setText(bean.getAccountAlipay());
                    mAlipayLayout.setStateNormal();
                    isAliPaly = true;
                }
//                微信支付账号
                if (StringUtils.isNoneNullString(bean.getAccountWechat())) {
                    mWechatPay.setText(bean.getAccountWechat());
                    mWechatLayout.setStateNormal();
                    isWechatPay = true;
                }
                //银行卡姓名
                if (StringUtils.isNoneNullString(bean.getAccountBankCardName())) {
                    mBankName.setText(bean.getAccountBankCardName());
                    mBankNameLayout.setStateNormal();
                    isBankName = true;
                }
                //银行卡开户行
                if (StringUtils.isNoneNullString(bean.getAccountBank())) {
                    mBankWhere.setText(bean.getAccountBank());
                    mBankLayout.setStateNormal();
                    isBankWhere = true;
                }
                //银行卡卡号
                if (StringUtils.isNoneNullString(bean.getAccountBankCardCode())) {
                    mBankNumber.setText(bean.getAccountBankCardCode());
                    mBankNumLayout.setStateNormal();
                    isBankNum = true;
                }
                //允许线下付
                if (StringUtils.isNoneNullString(bean.getPayOfflineFlag())) {
                    if (bean.getPayOfflineFlag().equals("0")) {
                        mCheckBox.setSelected(false);
                        mPlace.setSelected(false);
                    } else {
                        mCheckBox.setSelected(true);
                        mPlace.setSelected(true);
                    }
                }
                checkCanClick();
            }
        }
        if (getArguments() != null && getArguments().getString(ContractConstant.KEY_PAY_ITEM_PBUKID) != null) {
            mPbUkid = getArguments().getString(ContractConstant.KEY_PAY_ITEM_PBUKID);
        }
	    if (getArguments() != null && getArguments().getString(ContractConstant.KEY_MODIFY_PAYMENT_ITEM_CONTRACT_UKID) != null) {
		    mContractUkid = getArguments().getString(ContractConstant.KEY_MODIFY_PAYMENT_ITEM_CONTRACT_UKID);
	    }
	    bindEditText();

        mRelPlaceOrder.setOnClickListener(this);


    }

    @Override
    public void onSuccess(CommonClass commonClass, int what) {
        if (what == 1) {
            if (commonClass.getCode().equals("0")) {
                PayItemEvent payItemEvent = new PayItemEvent();
                String week = "";
                String month = "";
                String order = "";
                if (StringUtils.isNoneNullString(bean.getPayWeek()) && !bean.getPayWeek().equals("0") && !bean.getPayWeek().equals("-1")) {
                    week = "周付、";
                }
                if (StringUtils.isNoneNullString(bean.getPayMonth()) &&!bean.getPayMonth().equals("0") && !bean.getPayMonth().equals("-1") ) {
                    month = "月付、";
                }
                if (StringUtils.isNoneNullString(bean.getPayOrderFlag()) && !bean.getPayOrderFlag().equals("0") && !bean.getPayOrderFlag().equals("-1")) {
                    order = "下单付、";
                }
                String timeResult = "";
                 timeResult = week + month + order;
                String str1 = timeResult.substring(timeResult.length()-1);
                if (str1.equals("、")) {
                    timeResult = timeResult.substring(0, timeResult.length()-1);
                }
                payItemEvent.setPayTime(timeResult);
                String zhiFuBao = "";
                String weChat = "";
                String bank = "";
                String offline = "";
                if (mCheckBox.isSelected()) {
                    offline = "线下付、";
                }
                if (StringUtils.isNoneNullString(mAlipay.getText().toString().trim())) {
                    zhiFuBao = "支付宝、";
                }
                if (StringUtils.isNoneNullString(mWechatPay.getText().toString().trim())) {
                    weChat = "微信、";
                }
                if (StringUtils.isNoneNullString(mBankName.getText().toString().trim()) && StringUtils.isNoneNullString(mBankNumber.getText().toString().trim())
                        && StringUtils.isNoneNullString(mBankWhere.getText().toString().trim())) {
                    bank = "银行卡";
                }
                String result = offline + zhiFuBao + weChat + bank;
                if (StringUtils.isNoneNullString(result)) {
                    String str1Result = result.substring(result.length()-1, result.length());
                    if (str1Result.equals("、")) {
                        String resultStr = result.substring(0, result.length() - 1);
                        payItemEvent.setPayWay(resultStr);
                    } else {
                        payItemEvent.setPayWay(result);
                    }
                }
                EventBus.getDefault().post(payItemEvent);
                popFragment();
            } else {
                if (StringUtils.isNoneNullString(commonClass.getMsg()))
                toast(commonClass.getMsg());
            }
        } else if (what == 2) {
            if (commonClass.getCode().equals("0")) {
                popFragment();
                EventBus.getDefault().post(new RefreshPublishGoodsEvent("refresh"));
            }
        }

    }

    @Override
    public void onReLoad(int code) {

    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.rel_place_order) {
            mCheckBox.setSelected(!mCheckBox.isSelected());
            mPlace.setSelected(!mPlace.isSelected());
            checkCanClick();
        } else if (i == R.id.confirm_btn) {
	        //判断银行卡三条信息是否都填写完整
	        // step 1 .  判断三条信息是否有一条填写 ， 如果有，再判断三条是否都填了
	        boolean isOneInput;
	        isOneInput = StringUtils.isNoneNullString(mBankName.getText().toString().trim()) || StringUtils.isNoneNullString(mBankNumber.getText().toString().trim()) || StringUtils.isNoneNullString(mBankWhere.getText().toString().trim());
	        if (isOneInput) {
		        boolean isFullInput = StringUtils.isNoneNullString(mBankName.getText().toString().trim()) && StringUtils.isNoneNullString(mBankWhere.getText().toString().trim()) && StringUtils.isNoneNullString(mBankNumber.getText().toString().trim());
		        if (!isFullInput) {
			        toast("银行卡信息未填写完整");
			        return;
		        }
	        }
	        Map<String, Object> paramsMap = new HashMap<>();
            paramsMap.put("accountAlipay", mAlipay.getText().toString());
            paramsMap.put("accountBank", mBankWhere.getText().toString());
            paramsMap.put("accountBankCardCode", mBankNumber.getText().toString().replace(" " , ""));
            paramsMap.put("accountBankCardName", mBankName.getText().toString());
            paramsMap.put("accountWechat", mWechatPay.getText().toString());
            if (bean != null) {
                if (StringUtils.isNoneNullString(bean.getPayWeek())) {
                    paramsMap.put("payWeek", bean.getPayWeek());
                }
                if (StringUtils.isNoneNullString(bean.getPayMonth())) {
                    paramsMap.put("payMonth", bean.getPayMonth());
                }
                if (mCheckBox.isSelected()) {
                    paramsMap.put("payOfflineFlag", "1");
                } else {
                    paramsMap.put("payOfflineFlag", "0");
                }
                if (StringUtils.isNoneNullString(bean.getPayOrderFlag())) {
                    paramsMap.put("payOrderFlag", bean.getPayOrderFlag());
                }
                if (StringUtils.isNoneNullString(bean.getPaymentTempUkid())) {
                    paramsMap.put("paymentTempUkid", bean.getPaymentTempUkid());
                }
                if (StringUtils.isNoneNullString(bean.getPaymentPublishUkid())) {
                    paramsMap.put("paymentPublishUkid", bean.getPaymentPublishUkid());
                }
                if (getArguments() != null && StringUtils.isNoneNullString(getArguments().getString("isModify"))) {
                    paramsMap.put("contractUkid", mContractUkid);
                    httpPost(ContractConstant.METHOD_CONTRACT_PAYMENTS_MODIFY_CONFIRM ,  paramsMap , 2 , true , "正在保存...");
                } else {
                    paramsMap.put("pbUkid", mPbUkid);
                    httpPost(ContractConstant.PAY_MENTS_CONFIRM ,  paramsMap , 1 , true , "正在保存...");
                }
            }




        }
    }


    public void bindEditText() {
        mAlipay.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {


            }

            @Override
            public void afterTextChanged(Editable s) {
                if (StringUtils.isNoneNullString(s.toString())) {
                    boolean isPecial;
                    boolean isZh;
                    if (!s.toString().matches(specialSym)) {
                        isPecial = true;
                    } else {
                        isPecial = false;
                    }
                    if (isContainChinese(s.toString())) {
                        isZh = true;
                    } else {
                        isZh = false;
                    }
                    if (isPecial || isZh) {
                        mAlipayLayout.setStateWrong("不是有效的支付宝账号");
                        isAliPaly = false;
                    } else {
                        mAlipayLayout.setStateNormal();
                        isAliPaly = true;
                    }
                } else {
                    mAlipayLayout.setStateNormal();
                    isAliPaly = true;

                }
                checkCanClick();

            }
        });
        mWechatPay.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (StringUtils.isNoneNullString(s.toString())) {
                    if (s.toString().length() <= 40) {
                        mWechatLayout.setStateNormal();
                        isWechatPay = true;
                    } else {
                        mWechatLayout.setStateWrong("不是有效的微信账号");
                        isWechatPay = false;
                    }

                } else {
                    mWechatLayout.setStateNormal();

                }
                checkCanClick();
            }
        });

        mBankName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (StringUtils.isNoneNullString(s.toString())) {
                    if (s.toString().length() > 20) {
                        mBankNameLayout.setStateWrong("姓名不能超过20个字");
                        isBankName = false;
                    } else {
                        if (!s.toString().matches(specialSym)) {
                            mBankNameLayout.setStateWrong("不能包含特殊字符");
                            isBankName = false;
                        } else {
                            mBankNameLayout.setStateNormal();
                            isBankName = true;
                        }
                    }


                } else {
                    mBankNameLayout.setStateNormal();
                }
                checkCanClick();

            }
        });

        mBankWhere.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (StringUtils.isNoneNullString(s.toString())) {
                    if (s.toString().length() > 20) {
                        mBankLayout.setStateWrong("开户行名称不能超过20个字");
                        isBankWhere = false;
                    } else {
                        if (!s.toString().matches(specialSym)) {
                            mBankLayout.setStateWrong("不能包含特殊字符");
                            isBankWhere = false;
                        } else {
                            mBankLayout.setStateNormal();
                            isBankWhere = true;
                        }
                    }


                } else {
                    mBankLayout.setStateNormal();
                }
                checkCanClick();

            }
        });

        mBankNumber.addTextChangedListener(new TextWatcher() {
            private int oldLength = 0;
            private boolean isChange = true;
            private int curLength = 0;
            private int emptyNumB = 0;
            private int emptyNumA = 0;

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                oldLength = s.length();
                Log.i(TAG, "未改变长度: " + oldLength);
                emptyNumB = 0;
                for (int i = 0; i < s.toString().length(); i++) {
                    if (s.charAt(i)==' ') emptyNumB++;
                }
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                curLength = s.length();
                Log.i(TAG, "当前长度: " + curLength);
                if (curLength == oldLength || curLength <= 3) {
                    isChange = false;
                } else {
                    isChange = true;
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

                if (isChange) {
                    int selectIndex = mBankNumber.getSelectionEnd();//获取光标位置
                    String content = s.toString().replaceAll(" ", "");
                    Log.i(TAG, "content:" + content);
                    StringBuffer sb = new StringBuffer(content);
                    //遍历加空格
                    int index = 1;
                    emptyNumA = 0;
                    for (int i = 0; i < content.length(); i++) {
                        if ((i + 1) % 4 == 0) {
                            sb.insert(i + index, " ");
                            index++;
                            emptyNumA++;
                        }
                    }
                    Log.i(TAG, "result content:" + sb.toString());
                    String result = sb.toString();
                    if (result.endsWith(" ")) {
                        result = result.substring(0, result.length() - 1);
                    }
                    mBankNumber.setText(result);
                    if (emptyNumA > emptyNumB)
                        selectIndex = selectIndex + (emptyNumA - emptyNumB);
                    //处理光标位置
                    if (selectIndex > result.length()||selectIndex+1 == result.length()){
                        selectIndex = result.length();
                    }else if (selectIndex < 0){
                        selectIndex = 0;
                    }
                    mBankNumber.setSelection(selectIndex);
                    isChange = false;
                }


                if (StringUtils.isNoneNullString(s.toString())) {
                    if (s.toString().length() > 24) {
                        mBankNumLayout.setStateWrong("卡号不能超过20个字符");
                        isBankNum = false;
                    } else {
                        mBankNumLayout.setStateNormal();
                        isBankNum = true;

                    }

                } else {
                    mBankNumLayout.setStateNormal();
                }
                checkCanClick();

            }
        });
    }

    private void checkCanClick() {
        isOneInput = StringUtils.isNoneNullString(mBankNumber.getText().toString().trim()) && StringUtils.isNoneNullString(mBankWhere.getText().toString().trim())
                && StringUtils.isNoneNullString(mBankName.getText().toString().trim())
                || ((StringUtils.isNoneNullString(mWechatPay.getText().toString().trim()))
                || StringUtils.isNoneNullString(mAlipay.getText().toString().trim())) || mCheckBox.isSelected();
        if (isAliPaly && isWechatPay && isBankName && isBankWhere && isBankNum && isOneInput) {
            mConfirm.setEnabled(true);
            mConfirm.setBackground(mActivity.getResources().getDrawable(R.drawable.common_btn1_normal_shape));
        } else {
            mConfirm.setEnabled(false);
            mConfirm.setBackground(mActivity.getResources().getDrawable(R.drawable.common_btn1_noclick_shape));
        }
    }

    public static boolean isContainChinese(String str) {

        Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
        Matcher m = p.matcher(str);
        if (m.find()) {
            return true;
        }
        return false;

}
}
